package com.example.strategy;


import cn.hutool.core.util.StrUtil;
import com.example.entity.Coupon;
import com.example.entity.UserCoupon;
import com.example.util.BeanCopyPropertiesUtils;
import com.example.util.NumberUtils;
import lombok.RequiredArgsConstructor;

import java.math.BigDecimal;

/**
 * 折扣类型
 */
@RequiredArgsConstructor
public class RateDiscount implements Discount {

    private static final String RULE_TEMPLATE = "满{}打{}折，上限{}元";

    @Override
    public boolean canUse(BigDecimal totalAmount, UserCoupon coupon) {
        BigDecimal minPoint = new BigDecimal(coupon.getMinPoint());
        return totalAmount.compareTo(minPoint) >= 0;
    }

    @Override
    public BigDecimal calculateDiscount(BigDecimal totalAmount, UserCoupon coupon) {
        // 计算折扣，保持高精度计算
        BigDecimal hundred = BigDecimal.valueOf(100);
        BigDecimal discountAmount = totalAmount.multiply(hundred.subtract(new BigDecimal(coupon.getReduceAmount()))).divide(hundred);

        // 确保折扣金额不超过优惠券允许的最大抵扣金额
        BigDecimal maxDiscount = new BigDecimal(coupon.getMaxDiscountAmount());
        return discountAmount.min(maxDiscount);
    }



    @Override
    public String getRule( UserCoupon coupon) {
        return StrUtil.format(
                RULE_TEMPLATE,
                coupon.getMinPoint(),
                NumberUtils.scaleToStr(coupon.getReduceAmount(), 1),
                coupon.getMaxDiscountAmount()
        );
    }

    @Override
    public String getRule(Coupon coupon) {
        UserCoupon userCoupon = BeanCopyPropertiesUtils.copyBean(coupon, UserCoupon.class);
        return getRule(userCoupon);
    }
}
